<?php

namespace App\Common\Utils;

use Illuminate\Support\Facades\Request;

class GrayLogCustomProcessor
{
    public function __invoke(array $record): array
    {
        $debugBar = app('Barryvdh\Debugbar\LaravelDebugbar');
        $record['context']['request_id'] = $debugBar->getCurrentRequestId();
        [$ip, $url] = $this->getCurrentIpAndPathInfo();
        $record['context']['ip'] = $ip;
        $record['context']['uri'] = $url;
        try {
            $user = \Auth::user();
            if ($user !== null) {
                $record['context']['auth_class'] = get_class($user);
                $record['context']['auth_id'] = $user->getKey();
            }
        } catch (\Exception $e) {
        }

        return $record;
    }

    private function getCurrentIpAndPathInfo()
    {
        if (php_sapi_name() === 'cli') {
            $ip = '127.0.0.1';
            return [isset($_SERVER['SCRIPT_FILENAME']) ? realpath($_SERVER['SCRIPT_FILENAME']) : null, $ip];
        }

        return [
            Request::instance()->getClientIp(),
            Request::instance()->getPathInfo(),
        ];
    }
}
